package com.eastfair.venueservice.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.common.utils.Objects;
//import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.annotation.annotation.cache.Cache;
import com.eastfair.annotation.annotation.cache.Magic;
import com.eastfair.auth.api.AuthServiceFeign;
import com.eastfair.auth.api.UserAccountServiceFeign;
import com.eastfair.auth.dto.OrganizationDTO;
import com.eastfair.auth.entity.UserAccount;
import com.eastfair.auth.vo.OrganizationVo;
import com.eastfair.auth.vo.UserAccountVo;
import com.eastfair.boot.request.PageParams;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.builder.ExhibitorFeign;
import com.eastfair.builder.dto.ExhibitorDTO;
import com.eastfair.builder.vo.ExhibitorVO;
import com.eastfair.common.dto.AttachmentFileDTO;
import com.eastfair.common.vo.AttachmentFileVO;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.base.entity.SuperEntity;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.core.utils.ConvertUtil;
import com.eastfair.matching.api.MatchingMsgFeign;
import com.eastfair.messagecenter.api.MsgServiceFeign;
import com.eastfair.messagecenter.dto.InnerSendDTO;
import com.eastfair.messagecenter.dto.SmsSendDTO;
import com.eastfair.messagecenter.enumeration.ChannelType;
import com.eastfair.messagecenter.model.InnerContentModel;
import com.eastfair.messagecenter.model.SmsContentModel;
import com.eastfair.messagecenter.util.SmsSendDtoUtil;
import com.eastfair.pay.api.AttachmentFileFeign;
import com.eastfair.projectcore.enumeration.DataIsolationSystemSceneEnum;
import com.eastfair.venuebooking.enums.VenueBookingMoudleEnum;
import com.eastfair.venueservice.consts.CommonConstants;
import com.eastfair.venueservice.dao.WorkOrderMapper;
import com.eastfair.venueservice.dto.WorkOrderDTO;
import com.eastfair.venueservice.dto.WorkOrderDrawingDTO;
import com.eastfair.venueservice.dto.WorkOrderOperationRecordDTO;
import com.eastfair.venueservice.dto.WorkOrderQuery;
import com.eastfair.venueservice.entity.*;
import com.eastfair.venueservice.enumeration.*;
import com.eastfair.venueservice.service.*;
import com.eastfair.venueservice.vo.*;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.aop.framework.AopContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.eastfair.venueservice.enumeration.WorkOrderOperationRecordOperationTypeEnum.CREATE;

/**
* <p>
    * 业务实现类
    * 工单
    * </p>
*
* @author linan
* @date 2022-10-14
*/
@Slf4j
@Service
//@DS("#thread.tenant")
public class WorkOrderServiceImpl extends SuperServiceImpl<WorkOrderMapper, WorkOrder> implements WorkOrderService {

    public static final String NAME = "加班";
    public static final String WORK_ORDER_NO = "work_order_no";
    private static final int WORK_ORDER_NO_LENGTH = 5;

    @Resource
    private ServiceOrderService serviceOrderService;
    @Resource
    private VenueManageServiceOrderService venueManageServiceOrderService;
    @Resource
    private ServiceBookingService serviceBookingService;
    @Resource
    private ServiceProviderService serviceProviderService;
    @Resource
    private AuthServiceFeign authServiceFeign;
    @Resource
    private WorkOrderServiceItemService workOrderServiceItemService;
    @Resource
    private WorkOrderDrawingService workOrderDrawingService;
    @Resource
    private WorkOrderOperationRecordService workOrderOperationRecordService;
    @Resource
    private WorkOvertimeService workOvertimeService;
    @Resource
    private WorkOrderWorkOvertimeService workOrderWorkOvertimeService;
    @Resource
    private ServiceItemService serviceItemService;
    @Resource
    private ServiceItemDetailService serviceItemDetailService;
    @Resource
    private WorkOrderLinkService workOrderLinkService;
    @Resource
    private ServiceCategoryService serviceCategoryService;
    @Resource
    private ServiceSpecsService serviceSpecsService;
    @Resource
    private ExhibitionManageService exhibitionManageService;
    @Resource
    private RepairReportService repairReportService;
    @Resource
    private SpaceAcceptanceService spaceAcceptanceService;
    @Resource
    private MsgServiceFeign msgServiceFeign;
    @Resource
    private UserAccountServiceFeign userAccountServiceFeign;

    @Resource(name = "threadPoolTaskExecutor")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Resource
    private MatchingMsgFeign matchingMsgFeign;

    @Resource
    private ExhibitorFeign exhibitorFeign;

    @Resource
    private ServiceItemOrgService serviceItemOrgService;

    @Resource
    private AttachmentFileFeign attachmentFileFeign;

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
    */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<WorkOrder> modelList) {
    modelList.stream().forEach(s -> {
    s.setIsDeleted(BusinessConstant.YES);
    });
    // TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
    return R.successDef();
    }


    @Override
    protected R<Boolean> handlerSave(WorkOrder model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        // 推站内信
        sendInnerMsgForOrg(model);
        return R.successDef();
    }

    /**
     * 推站内信
     * @param model
     */
    private void sendInnerMsgForOrg(WorkOrder model) {
        Long acceptCompanyId = model.getAcceptCompanyId();
        String acceptSubjectType = model.getAcceptSubjectType();
        InnerSendDTO innerSendDTO = new InnerSendDTO();
        innerSendDTO.setBusinessType(BusinessConstant.BUSINESS_COMMON);
        innerSendDTO.setChannelType(ChannelType.INNER_IM);
        innerSendDTO.setBusinessId(ContextUtil.getTrace());
        InnerContentModel innerContentModel = new InnerContentModel();
        Map<String, Object> contentMap = new HashMap<>();
        contentMap.put("content", String.format("有新工单需要处理，编号；%s", model.getWorkOrderNo()));
        innerContentModel.setContentMap(contentMap);
        innerSendDTO.setInnerContentModelList(Arrays.asList(innerContentModel));
        if(DataIsolationSystemSceneEnum.P_COMPOSITE_MATING.getCode().equals(acceptSubjectType)){
            innerSendDTO.setTeamId(acceptCompanyId);
            innerSendDTO.setIsSendAll(true);
            threadPoolTaskExecutor.execute(()->{
                matchingMsgFeign.sendInnerInMsg(innerSendDTO);
            });
        }else {
            Set<Long> orgIdList = new HashSet<>();
            orgIdList.add(acceptCompanyId);
            innerSendDTO.setOrgIdList(orgIdList);
            threadPoolTaskExecutor.execute(()->{
                msgServiceFeign.sendInnerInMsg(innerSendDTO);
            });
        }
    }

    /**
     * 推短信
     * @param model
     * @param reassignUserId
     */
    private void sendMsgForUser(WorkOrder model, Long reassignUserId) {
        String content =StringUtils.isNotBlank(model.getWorkOrderDesc())?
                String.format("您有新的工单：编号：%s，工单描述：%s，请及时处理！",model.getWorkOrderNo(),model.getWorkOrderDesc())
                : String.format("您有新的工单：编号：%s，请及时处理！",model.getWorkOrderNo());
        // 获取处理人
        try{
            R<UserAccount> userAccountR = userAccountServiceFeign.get(reassignUserId);
            String mobile = userAccountR.getData().getMobile();
            Set<String> nums = new HashSet<>();
            nums.add(mobile);
            msgServiceFeign.sendSmsMsg(SmsSendDtoUtil.sendSmsDto(CommonConstants.BUSINESS_COMMON, nums, content));
        }catch (Exception e){
            log.error("推送短息失败",e);
        }
    }

    /**
    * 通用查询
    *
    * @param modelDTO DTO
    * @param ids 主键id集合
    * @return list
    */
    @Override
    public List<WorkOrder> list(WorkOrderDTO modelDTO, List<Long> ids) {
        return ((WorkOrderService) AopContext.currentProxy()).listOfCache(modelDTO, ids);
    }


    /**
     * 缓存查询
     *
     * @param modelDTO DTO
     * @param ids 主键id集合
     * @return list
     */
    @Override
    @Cache(key = "",
       magic = @Magic(
       key = "{"+
       "{'isEnabled', #args[0]?.isEnabled},"+
       "{'orderNumber', #args[0]?.orderNumber},"+
       "{'workOrderNo', #args[0]?.workOrderNo},"+
       "{'exhibitionManageId', #args[0]?.exhibitionManageId},"+
       "{'workOrderType', #args[0]?.workOrderType},"+
       "{'workOrderStatus', #args[0]?.workOrderStatus},"+
       "{'customerSubjectId', #args[0]?.customerSubjectId},"+
       "{'customerSubjectName', #args[0]?.customerSubjectName},"+
       "{'customerSubjectType', #args[0]?.customerSubjectType},"+
       "{'contact', #args[0]?.contact},"+
       "{'contactMobile', #args[0]?.contactMobile},"+
       "{'spaceCode', #args[0]?.spaceCode},"+
       "{'spaceName', #args[0]?.spaceName},"+
       "{'siteCode', #args[0]?.siteCode},"+
       "{'siteName', #args[0]?.siteName},"+
       "{'acceptSubjectType', #args[0]?.acceptSubjectType},"+
       "{'acceptCompanyId', #args[0]?.acceptCompanyId},"+
       "{'acceptCompanyName', #args[0]?.acceptCompanyName},"+
       "{'payAmount', #args[0]?.payAmount},"+
       "{'payWay', #args[0]?.payWay},"+
       "{'payTime', #args[0]?.payTime},"+
       "{'remark', #args[0]?.remark},"+
       "{'workOrderDesc', #args[0]?.workOrderDesc},"+
        "{'id', #args[1]}"+
        "}"))
    public List<WorkOrder> listOfCache(WorkOrderDTO modelDTO, List<Long> ids) {
       //查询
       QueryWrapper<WorkOrder> queryWrapper = new QueryWrapper<>();
       if (modelDTO != null) {
                    queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getOrderNumber()),WorkOrder::getOrderNumber,modelDTO.getOrderNumber());
                    queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getWorkOrderNo()),WorkOrder::getWorkOrderNo,modelDTO.getWorkOrderNo());
                    queryWrapper.lambda().eq(modelDTO.getExhibitionManageId() != null,WorkOrder::getExhibitionManageId,modelDTO.getExhibitionManageId());
                    queryWrapper.lambda().eq(Objects.nonNull(modelDTO.getWorkOrderType()),WorkOrder::getWorkOrderType,modelDTO.getWorkOrderType());
                    queryWrapper.lambda().eq(Objects.nonNull(modelDTO.getWorkOrderStatus()),WorkOrder::getWorkOrderStatus,modelDTO.getWorkOrderStatus());
                    queryWrapper.lambda().eq(modelDTO.getCustomerSubjectId() != null,WorkOrder::getCustomerSubjectId,modelDTO.getCustomerSubjectId());
                    queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getCustomerSubjectName()),WorkOrder::getCustomerSubjectName,modelDTO.getCustomerSubjectName());
                    queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getCustomerSubjectType()),WorkOrder::getCustomerSubjectType,modelDTO.getCustomerSubjectType());
                    queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getContact()),WorkOrder::getContact,modelDTO.getContact());
                    queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getContactMobile()),WorkOrder::getContactMobile,modelDTO.getContactMobile());
                    queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getSpaceCode()),WorkOrder::getSpaceCode,modelDTO.getSpaceCode());
                    queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getSpaceName()),WorkOrder::getSpaceName,modelDTO.getSpaceName());
                    queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getSiteCode()),WorkOrder::getSiteCode,modelDTO.getSiteCode());
                    queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getSiteName()),WorkOrder::getSiteName,modelDTO.getSiteName());
                    queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getAcceptSubjectType()),WorkOrder::getAcceptSubjectType,modelDTO.getAcceptSubjectType());
                    queryWrapper.lambda().eq(modelDTO.getAcceptCompanyId() != null,WorkOrder::getAcceptCompanyId,modelDTO.getAcceptCompanyId());
                    queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getAcceptCompanyName()),WorkOrder::getAcceptCompanyName,modelDTO.getAcceptCompanyName());
                    queryWrapper.lambda().eq(modelDTO.getPayAmount() != null,WorkOrder::getPayAmount,modelDTO.getPayAmount());
                    queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getPayWay()),WorkOrder::getPayWay,modelDTO.getPayWay());
                    queryWrapper.lambda().eq(modelDTO.getPayTime() != null,WorkOrder::getPayTime,modelDTO.getPayTime());
                    queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getRemark()),WorkOrder::getRemark,modelDTO.getRemark());
                    queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getWorkOrderDesc()),WorkOrder::getWorkOrderDesc,modelDTO.getWorkOrderDesc());
            }
            if (ids != null && !ids.isEmpty()) {
            queryWrapper.lambda().in(WorkOrder::getId, ids);
            }
            queryWrapper.lambda().eq(WorkOrder::getIsDeleted, BusinessConstant.DELETE_NO);
            List<WorkOrder> modelList = list(queryWrapper);
            return modelList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer generateWorkOrder(WorkOrderDTO workOrderDTO) {
        Integer resultNum = 0;
        WorkOrderWorkOrderTypeEnum workOrderType = workOrderDTO.getWorkOrderType();
        // 生成服务工单
        if(workOrderType.eq(WorkOrderWorkOrderTypeEnum.SERVICE)){
            resultNum += generateServiceWorkOrder(workOrderDTO);
        }

        // 生成加班工单
        if(workOrderType.eq(WorkOrderWorkOrderTypeEnum.WORK_OVERTIME)){
             generateWorkOvertimeWorkOrder(workOrderDTO);
            resultNum += 1;
        }

        // 生成报修工单
        if(workOrderType.eq(WorkOrderWorkOrderTypeEnum.REPAIR)){
             generateRepairWorkOrder(workOrderDTO);
            resultNum += 1;
        }

        // 生成验收工单
        if(workOrderType.eq(WorkOrderWorkOrderTypeEnum.CHECK)){
             generateCheckWorkOrder(workOrderDTO);
            resultNum += 1;
        }

        return resultNum;
    }

    /**
     * 生成服务工单
     * @param workOrderDTO
     */
    private Integer generateServiceWorkOrder(WorkOrderDTO workOrderDTO) {
        Integer resultNum = 0;
        // 先判断是否有订单号
        String orderNumber = workOrderDTO.getOrderNumber();
        if(StringUtils.isNotBlank(orderNumber)){
            // 订单-》派工单
            List<WorkOrderDrawingDTO> workOrderDrawings = workOrderDTO.getWorkOrderDrawings();
            // 查询订单详情
            ServiceOrder serviceOrder = serviceOrderService.getByOrderNumber(orderNumber);
            // 查询订单服务
            List<ServiceBookingVO> serviceBookingVOS = new ArrayList<>();
            // 处理服务来源
            for (ServiceBookingVO serviceBookingVO : serviceBookingService.queryServiceBookingListByOrderNumber(Collections.singletonList(orderNumber))) {
                if(Objects.nonNull(serviceBookingVO.getSourceId())){
                    // 查询最底层服务来源
                    ServiceItem serviceItem = serviceItemService.getDeapSourceServiceItem(serviceBookingVO.getSourceId());
                    serviceBookingVO.setServiceItemId(serviceItem.getId());
                    serviceBookingVO.setServiceProviderType(serviceItem.getServiceProviderType());
                    // 查询明细价格
                    ServiceItemDetail serviceItemDetail = serviceItemDetailService.getOne(new QueryWrapper<ServiceItemDetail>().lambda()
                            .eq(ServiceItemDetail::getIsDeleted, BusinessConstant.NO)
                            .eq(ServiceItemDetail::getServiceItemId, serviceItem.getId())
                            .eq(ServiceItemDetail::getServiceCategoryId, serviceBookingVO.getServiceCategoryId())
                            .eq(ServiceItemDetail::getServiceSpecsId, serviceBookingVO.getServiceSpecsId()));
                    if(Objects.nonNull(serviceItemDetail)){
                        serviceBookingVO.setUnitPrice(serviceItemDetail.getUnitPrice());
                    }
                    // 处理派多部门
                    List<ServiceItemOrg> serviceItemOrgs = serviceItemOrgService.list(new QueryWrapper<ServiceItemOrg>().lambda()
                            .eq(ServiceItemOrg::getIsDeleted, BusinessConstant.NO)
                            .eq(ServiceItemOrg::getServiceItemId, serviceItem.getId()));
                    for (ServiceItemOrg serviceItemOrg : serviceItemOrgs) {
                        ServiceBookingVO newServiceBookingVO = BeanUtil.copyProperties(serviceBookingVO, ServiceBookingVO.class);
                        newServiceBookingVO.setServiceProviderId(serviceItemOrg.getServiceProviderId());
                        serviceBookingVOS.add(newServiceBookingVO);
                    }
                }else {
                    // 处理派多部门
                    List<ServiceItemOrg> serviceItemOrgs = serviceItemOrgService.list(new QueryWrapper<ServiceItemOrg>().lambda()
                            .eq(ServiceItemOrg::getIsDeleted, BusinessConstant.NO)
                            .eq(ServiceItemOrg::getServiceItemId, serviceBookingVO.getServiceItemId()));
                    for (ServiceItemOrg serviceItemOrg : serviceItemOrgs) {
                        ServiceBookingVO newServiceBookingVO = BeanUtil.copyProperties(serviceBookingVO, ServiceBookingVO.class);
                        newServiceBookingVO.setServiceProviderId(serviceItemOrg.getServiceProviderId());
                        serviceBookingVOS.add(newServiceBookingVO);
                    }
                }
            }
            Map<Long, List<ServiceBookingVO>> serviceBookingMap = serviceBookingVOS.stream().collect(Collectors.groupingBy(ServiceBookingVO::getServiceProviderId));
            List<Long> serviceProviderIds = new ArrayList<>(serviceBookingMap.keySet());
            // 服务商名称
            Map<Long, ServiceProviderVO> serviceProviderMap = serviceProviderService.listServiceProviderByIds(serviceProviderIds).stream().collect(Collectors.toMap(ServiceProviderVO::getId, Function.identity()));
            // 部门名称
            R<List<OrganizationVo>> listR = authServiceFeign.queryList(serviceProviderIds);
            if(!listR.getIsSuccess()){
                throw BizException.wrap(listR.getCode(),listR.getMsg());
            }
            Map<Long, OrganizationVo> orgMap = new HashMap<>();
            if(Objects.nonNull(listR.getData())){
                orgMap = listR.getData().stream().collect(Collectors.toMap(OrganizationVo::getId, Function.identity()));
            }
            AtomicInteger serialNo = new AtomicInteger(1);
            resultNum += dealWorkOrder(workOrderDTO.getWorkOrderOperationRecordDTO(),orderNumber, workOrderDrawings, serviceOrder, serviceBookingVOS, serviceBookingMap, serviceProviderMap, orgMap, serialNo);
            // 更新订单派单状态
            venueManageServiceOrderService.updateWorkOrderStatusHasDispatch(serviceOrder.getOrderNumber());
        } else {
            // 报馆记录-》派工单
            resultNum +=generateServiceWorkOrderOfReportSpace(workOrderDTO);
        }
        return resultNum;
    }

    /**
     * 报馆记录-》派工单
     * @param workOrderDTO workOrderDTO
     * @return
     */
    private int generateServiceWorkOrderOfReportSpace(WorkOrderDTO workOrderDTO) {
        String prefix = LocalDateTimeUtil.format(LocalDate.now(), "yyyyMMdd");
        String workOrderNo = CreatCode.creatCode(baseMapper, WORK_ORDER_NO, WORK_ORDER_NO_LENGTH, prefix);
        Long reportSpaceServiceId = workOrderDTO.getReportSpaceServiceId();
        ServiceBooking serviceBooking = serviceBookingService.getById(reportSpaceServiceId);
        Long serviceItemId = serviceBooking.getServiceItemId();
        ServiceItem serviceItem = serviceItemService.getDeapSourceServiceItem(serviceItemId);
        List<Long> serviceProviderIds = serviceItemOrgService.list(new QueryWrapper<ServiceItemOrg>().lambda()
                .eq(ServiceItemOrg::getIsDeleted, BusinessConstant.NO)
                .eq(ServiceItemOrg::getServiceItemId, serviceItem.getId())).stream().map(ServiceItemOrg::getServiceProviderId).collect(Collectors.toList());
        // 服务商名称
        Map<Long, ServiceProviderVO> serviceProviderMap = serviceProviderService.listServiceProviderByIds(serviceProviderIds).stream().collect(Collectors.toMap(ServiceProviderVO::getId, Function.identity()));
        // 部门名称
        R<List<OrganizationVo>> listR = authServiceFeign.queryList(serviceProviderIds);
        if(!listR.getIsSuccess()){
            throw BizException.wrap(listR.getCode(),listR.getMsg());
        }
        Map<Long, OrganizationVo> orgMap =new HashMap<>(8);
        if(Objects.nonNull(listR.getData())){
            orgMap = listR.getData().stream().collect(Collectors.toMap(OrganizationVo::getId, Function.identity()));
        }

        for (int i = 0; i < serviceProviderIds.size(); i++) {
            Long serviceProviderId = serviceProviderIds.get(i);
            WorkOrder workOrder = new WorkOrder();
            serviceItem.setServiceProviderId(serviceProviderId);
            dealSimpleProp(workOrderDTO, workOrderNo+"-"+(i+1), serviceBooking, serviceItem, workOrder);
            ServiceProviderVO serviceProviderVO = serviceProviderMap.get(serviceItem.getServiceProviderId());
            OrganizationVo organizationVo = orgMap.get(serviceProviderId);
            if(Objects.nonNull(serviceProviderVO)){
                workOrder.setAcceptCompanyName(serviceProviderVO.getCompanyName());
                workOrder.setAcceptSubjectType(DataIsolationSystemSceneEnum.P_COMPOSITE_MATING.getCode());
            }
            if(Objects.nonNull(organizationVo)){
                workOrder.setAcceptCompanyName(organizationVo.getName());
                workOrder.setAcceptSubjectType(DataIsolationSystemSceneEnum.P_COMPOSITE_VENUE.getCode());
            }
            BigDecimal workOrderAmount = BigDecimal.ZERO;
            // 处理其他明细
            dealOtherDetail(workOrderDTO, workOrderNo+"-"+(i+1), serviceBooking, workOrder, workOrderAmount);
            // 处理工单环节
            dealWorkOrderLink(workOrderDTO.getWorkOrderOperationRecordDTO(),WorkOrderLinkOperationTypeEnum.CREATE,workOrderNo+"-"+(i+1));
            // 推部门负责人短信
            sendMsgToLeader(workOrder);
            // 保存派工单
            save(workOrder);
        }
        // 更新报馆服务派工状态
        updateServiceBookingWorkOrderStatus(workOrderNo,serviceBooking,ServiceBookingWorkOrderStatusEnum.HAS_DISPATCH);
        // 更新订单派工状态
        ServiceBooking booking = serviceBookingService.getById(Long.parseLong(serviceBooking.getOrderNumber()));
        if(Objects.isNull(booking)){
            throw new BizException("历史数据无法处理，请联系开发人员及时处理");
        }
        String orderNumber = booking.getOrderNumber();
        // 查询总报馆服务条数和已报馆条数
        int count = serviceBookingService.count(new QueryWrapper<ServiceBooking>()
                .eq("is_deleted", BusinessConstant.NO)
                .eq("order_number", orderNumber));
        int countOfHasDispatch = serviceBookingService.count(new QueryWrapper<ServiceBooking>()
                .eq("is_deleted", BusinessConstant.NO)
                .eq("work_order_status", ServiceBookingWorkOrderStatusEnum.HAS_DISPATCH)
                .eq("order_number", orderNumber));
        ServiceOrderWorkOrderStatusEnum toUpdateStatus = null;
        if (count == countOfHasDispatch) {
            toUpdateStatus = ServiceOrderWorkOrderStatusEnum.HAS_DISPATCH;
        }else if(countOfHasDispatch == 0){
            toUpdateStatus = ServiceOrderWorkOrderStatusEnum.NOT_DISPATCH;
        }else {
            toUpdateStatus = ServiceOrderWorkOrderStatusEnum.PARTIAL_DISPATCH;
        }
        // 更新订单的派工状态
        venueManageServiceOrderService.updateWorkOrderStatus(orderNumber, toUpdateStatus);
        return serviceProviderIds.size();
    }

    /**
     * 推部门负责人短信
     * @param workOrder
     */
    private void sendMsgToLeader(WorkOrder workOrder) {
        Long acceptCompanyId = workOrder.getAcceptCompanyId();
        String acceptSubjectType = workOrder.getAcceptSubjectType();
        if(DataIsolationSystemSceneEnum.P_COMPOSITE_MATING.getCode().equals(acceptSubjectType)){
            ServiceProvider serviceProvider = serviceProviderService.getById(acceptCompanyId);
            try{
                threadPoolTaskExecutor.execute(()->{
                    String content =StringUtils.isNotBlank(workOrder.getWorkOrderDesc())?
                            String.format("您有新的工单：编号：%s，工单描述：%s，请及时处理！", workOrder.getWorkOrderNo(), workOrder.getWorkOrderDesc())
                            : String.format("您有新的工单：编号：%s，请及时处理！", workOrder.getWorkOrderNo());
                    // 获取处理人
                    Set<String> nums = new HashSet<>();
                    nums.add(serviceProvider.getPrincipalPhone());
                    msgServiceFeign.sendSmsMsg(SmsSendDtoUtil.sendSmsDto(CommonConstants.BUSINESS_COMMON, nums, content));
                });
            }catch (Exception e){
                log.error("发送短信失败", e);
            }
        }else {
            OrganizationDTO organizationDTO = new OrganizationDTO();
            organizationDTO.setOrgId(acceptCompanyId);
            R<List<UserAccountVo>> allLeaderUserOfOrg = userAccountServiceFeign.findAllLeaderUserOfOrg(organizationDTO);
            try{
                if(CollectionUtils.isEmpty(allLeaderUserOfOrg.getData())){
                    log.error("未找到部门负责人,{}", acceptCompanyId);
                }
                threadPoolTaskExecutor.execute(()->{
                    for (UserAccountVo userAccountVo : allLeaderUserOfOrg.getData()) {
                        sendMsgForUser(workOrder, userAccountVo.getId());
                    }
                });
            }catch (Exception e){
                log.error("发送短信失败", e);
            }
        }
    }

    /**
     * 更新报馆服务派工状态
     * @param workOrderNo
     * @param serviceBooking serviceBooking
     * @param workOrderStatusEnum workOrderStatusEnum
     */
    private void updateServiceBookingWorkOrderStatus(String workOrderNo, ServiceBooking serviceBooking, ServiceBookingWorkOrderStatusEnum workOrderStatusEnum) {
        serviceBookingService.update(new UpdateWrapper<ServiceBooking>().lambda()
                .in(SuperEntity::getId, Arrays.asList( serviceBooking.getId(), serviceBooking.getOrderNumber()))
                .set(StringUtils.isNotBlank(workOrderNo) ,ServiceBooking::getWorkOrderNo,workOrderNo)
                .set(ServiceBooking::getWorkOrderStatus,workOrderStatusEnum));
    }

    /**
     * 处理工单基础信息
     * @param workOrderDTO workOrderDTO
     * @param workOrderNo workOrderNo
     * @param serviceBooking serviceBooking
     * @param serviceItem serviceItem
     * @param workOrder workOrder
     */
    private void dealSimpleProp(WorkOrderDTO workOrderDTO, String workOrderNo, ServiceBooking serviceBooking, ServiceItem serviceItem, WorkOrder workOrder) {
        // 展会
        workOrder.setExhibitionManageId(serviceBooking.getExhibitionManageId());
        // 生成工单编号
        workOrder.setWorkOrderNo(workOrderNo);
        // 企业名称
        workOrder.setCustomerSubjectId(serviceBooking.getBusinessId());
        // 查询企业明细
        if(Objects.nonNull(serviceBooking.getBusinessId())){
            ServiceProvider serviceProvider = serviceProviderService.getById(serviceBooking.getBusinessId());
            // 联系人
            workOrder.setContact(serviceProvider.getPrincipalName());
            // 联系方式
            workOrder.setContactMobile(serviceProvider.getPrincipalPhone());
            workOrder.setCustomerSubjectName(serviceProvider.getCompanyName());
        }else {
            // 涉及到客展报馆
            ExhibitorDTO exhibitorDTO = new ExhibitorDTO();
            exhibitorDTO.setExhibitorName(serviceBooking.getExhibitorName());
            exhibitorDTO.setSpaceName(serviceBooking.getSpaceName());
            exhibitorDTO.setSiteName(serviceBooking.getSiteName());
            exhibitorDTO.setPerfectMatch(true);
            R<List<ExhibitorVO>> listR = exhibitorFeign.queryExhibitors(exhibitorDTO);
            for (ExhibitorVO exhibitorVO : listR.getData()) {
                // 联系人
                workOrder.setContact(exhibitorVO.getContact());
                // 联系方式
                workOrder.setContactMobile(exhibitorVO.getContactMobile());
                workOrder.setCustomerSubjectName(exhibitorVO.getBuilderName());
            }
        }

        // 展厅号
        workOrder.setSpaceCode(serviceBooking.getSpaceCode());
        workOrder.setSpaceName(serviceBooking.getSpaceName());
        // 展位号
        workOrder.setSiteName(serviceBooking.getSiteName());
        // 工单类型
        workOrder.setWorkOrderType(WorkOrderWorkOrderTypeEnum.SERVICE);
        // 工单状态
        workOrder.setWorkOrderStatus(WorkOrderWorkOrderStatusEnum.ORDER_TO_BE_RECEIVED);
        // 工单接受方
        workOrder.setAcceptCompanyId(serviceItem.getServiceProviderId());
        // 工单金额
        // 查询明细价格
        ServiceItemDetail serviceItemDetail = serviceItemDetailService.getOne(new QueryWrapper<ServiceItemDetail>().lambda()
                .eq(ServiceItemDetail::getIsDeleted, BusinessConstant.NO)
                .eq(ServiceItemDetail::getServiceItemId, serviceItem.getId())
                .eq(ServiceItemDetail::getServiceCategoryId, serviceBooking.getServiceCategoryId())
                .eq(ServiceItemDetail::getServiceSpecsId, serviceBooking.getServiceSpecsId()));
        if(Objects.nonNull(serviceItemDetail)){
            workOrder.setWorkOrderAmount(serviceItemDetail.getUnitPrice().multiply(BigDecimal.valueOf(serviceBooking.getBookingNum())));
        }
    }

    /**
     * 处理其他明细
     * @param workOrderDTO workOrderDTO
     * @param workOrderNo workOrderNo
     * @param serviceBooking serviceBooking
     * @param workOrder workOrder
     * @param workOrderAmount workOrderAmount
     */
    private void dealOtherDetail(WorkOrderDTO workOrderDTO, String workOrderNo, ServiceBooking serviceBooking, WorkOrder workOrder, BigDecimal workOrderAmount) {
        // 处理服务来源
        // 查询最底层服务来源
        ServiceItem serviceItem = serviceItemService.getDeapSourceServiceItem(serviceBooking.getServiceItemId());
        serviceBooking.setServiceItemId(serviceItem.getId());
        // 查询明细价格
        ServiceItemDetail serviceItemDetail = serviceItemDetailService.getOne(new QueryWrapper<ServiceItemDetail>().lambda()
                .eq(ServiceItemDetail::getIsDeleted, BusinessConstant.NO)
                .eq(ServiceItemDetail::getServiceItemId, serviceItem.getId())
                .eq(ServiceItemDetail::getServiceCategoryId, serviceBooking.getServiceCategoryId())
                .eq(ServiceItemDetail::getServiceSpecsId, serviceBooking.getServiceSpecsId()));
        if (Objects.nonNull(serviceItemDetail)) {
            serviceBooking.setUnitPrice(serviceItemDetail.getUnitPrice());
        }
        // 服务项
        WorkOrderServiceItem workOrderServiceItem = new WorkOrderServiceItem();
        BeanUtil.copyProperties(serviceBooking,workOrderServiceItem, CommonConstants.COMMON_IGNORE_PROPERTIES);
        // 查询服务分类名称和规格名称
        ServiceCategory serviceCategory = serviceCategoryService.getById(serviceBooking.getServiceCategoryId());
        ServiceSpecs serviceSpecs = serviceSpecsService.getById(serviceBooking.getServiceSpecsId());
        if(Objects.nonNull(serviceCategory)){
            workOrderServiceItem.setServiceCategoryName(serviceCategory.getServiceCategoryName());
        }
        if(Objects.nonNull(serviceSpecs)){
            workOrderServiceItem.setServiceSpecsName(serviceSpecs.getServiceSpecsName());
        }
        workOrderServiceItem.setWorkOrderNo(workOrderNo);
        workOrderServiceItem.setNum(BigDecimal.valueOf(serviceBooking.getBookingNum()));
        workOrderServiceItem.setSubtotalServicePrice(workOrderServiceItem.getUnitPrice().multiply(workOrderServiceItem.getNum()));
        workOrderAmount = workOrderAmount.add(workOrderServiceItem.getSubtotalServicePrice());
        workOrderServiceItemService.save(workOrderServiceItem);
        // 图纸
        List<WorkOrderDrawingDTO> workOrderDrawings = workOrderDTO.getWorkOrderDrawings();
        if(CollectionUtils.isNotEmpty(workOrderDrawings)){
            workOrderDrawings.forEach(value ->{
                WorkOrderDrawing workOrderDrawing = new WorkOrderDrawing();
                BeanUtil.copyProperties(value,workOrderDrawing);
                workOrderDrawing.setWorkOrderNo(workOrderNo);
                workOrderDrawingService.save(workOrderDrawing);
            });
        }
        WorkOrderOperationRecordDTO workOrderOperationRecordDTO = workOrderDTO.getWorkOrderOperationRecordDTO();
        // 生成操作记录
        WorkOrderOperationRecord workOrderOperationRecord = new WorkOrderOperationRecord();
        BeanUtil.copyProperties(workOrderOperationRecordDTO,workOrderOperationRecord);
        workOrderOperationRecord.setWorkOrderNo(workOrderNo);
        workOrderOperationRecord.setOperationType(CREATE);
        workOrderOperationRecord.setOperationRecordType(WorkOrderOperationRecordOperationRecordTypeEnum.CREATE);
        workOrderOperationRecord.setLastLinkFinishTime(serviceBooking.getReportSpaceTime());
        workOrderOperationRecordService.save(workOrderOperationRecord);
        workOrder.setWorkOrderAmount(workOrderAmount);
    }

    /**
     * 生成加班工单
     * @param workOrderDTO
     */
    private void generateWorkOvertimeWorkOrder(WorkOrderDTO workOrderDTO) {
        String orderNumber = workOrderDTO.getOrderNumber();
        // 获取加班申请详情
        WorkOvertime workOvertime = workOvertimeService.getByWorkOvertimeNumber(orderNumber);
        if(Objects.nonNull(workOvertime)){
            // 订单提交时间
            LocalDateTime orderTime = workOvertime.getCreateTime();
            AtomicInteger serialNo = new AtomicInteger(1);
            WorkOrder workOrder = new WorkOrder();
            // 展会
            workOrder.setExhibitionManageId(workOvertime.getExhibitionManageId());
            // 生成工单编号
            String workOrderNo = orderNumber +"-"+ serialNo;
            serialNo.getAndIncrement();
            workOrder.setWorkOrderNo(workOrderNo);
            workOrder.setOrderNumber(orderNumber);
            // 企业名称
            workOrder.setCustomerSubjectId(workOvertime.getCompanyId());
            workOrder.setCustomerSubjectName(workOvertime.getCompanyName());
            workOrder.setCustomerSubjectType(workOvertime.getCompanyType());
            // 联系人
            workOrder.setContact(workOvertime.getContact());
            // 联系方式
            workOrder.setContactMobile(workOvertime.getPhone());
            // 展厅号
            workOrder.setSpaceCode(workOvertime.getSpaceCode());
            workOrder.setSpaceName(workOvertime.getSpaceName());
            // 展位号
            workOrder.setSiteName(workOvertime.getSiteName());
            // 工单类型
            workOrder.setWorkOrderType(WorkOrderWorkOrderTypeEnum.WORK_OVERTIME);
            // 工单状态
            workOrder.setWorkOrderStatus(WorkOrderWorkOrderStatusEnum.ORDER_TO_BE_RECEIVED);
            // 工单接受方
            workOrder.setAcceptCompanyId(workOrderDTO.getAcceptCompanyId());
            workOrder.setAcceptCompanyName(workOrderDTO.getAcceptCompanyName());
            workOrder.setAcceptSubjectType(DataIsolationSystemSceneEnum.P_COMPOSITE_VENUE.getCode());
            BigDecimal workOrderAmount = BigDecimal.ZERO;
            // 加班申请详情
            WorkOrderWorkOvertime workOrderWorkOvertime = new WorkOrderWorkOvertime();
            workOrderWorkOvertime.setWorkOrderNo(workOrderNo);
            workOrderWorkOvertime.setName(NAME);
            workOrderWorkOvertime.setOvertimeDate(workOvertime.getOvertimeDate());
            if (workOvertime.getOvertimeStart() != null) {
                workOrderWorkOvertime.setOvertimeStart(workOvertime.getOvertimeStart().toString());
            }
            if (workOvertime.getOvertimeEnd() != null) {
                workOrderWorkOvertime.setOvertimeEnd(workOvertime.getOvertimeEnd().toString());
            }
            workOrderWorkOvertime.setOvertimePeriod(workOvertime.getReportOvertimePeriod());
            workOrderWorkOvertimeService.save(workOrderWorkOvertime);
            // 生成操作记录
            WorkOrderOperationRecord workOrderOperationRecord = new WorkOrderOperationRecord();
            BeanUtil.copyProperties(workOrderDTO.getWorkOrderOperationRecordDTO(),workOrderOperationRecord);
            workOrderOperationRecord.setWorkOrderNo(workOrderNo);
            workOrderOperationRecord.setOperationType(CREATE);
            workOrderOperationRecord.setOperationRecordType(WorkOrderOperationRecordOperationRecordTypeEnum.CREATE);
            workOrderOperationRecord.setLastLinkFinishTime(orderTime);
            workOrderOperationRecordService.save(workOrderOperationRecord);
            workOrder.setWorkOrderAmount(workOrderAmount);
            // 处理操作环节
            dealWorkOrderLink(workOrderDTO.getWorkOrderOperationRecordDTO(),WorkOrderLinkOperationTypeEnum.CREATE,workOrderNo);
            // 推部门负责人短信
            sendMsgToLeader(workOrder);
            save(workOrder);
        }
        // 更新加班记录的派工状态
        WorkOvertime updateEntity2 = new WorkOvertime();
        updateEntity2.setId(workOvertime.getId());
        updateEntity2.setWorkOrderStatus(WorkOvertimeWorkOrderStatusEnum.HAS_DISPATCH.getCode());
        workOvertimeService.updateById(updateEntity2);
    }

    /**
     * 生成验收工单
     * @param workOrderDTO
     */
    private void generateCheckWorkOrder(WorkOrderDTO workOrderDTO) {
        String orderNumber = workOrderDTO.getOrderNumber();
        // 获取加班申请详情
        SpaceAcceptance spaceAcceptance = spaceAcceptanceService.getByAcceptNo(orderNumber);
        if(Objects.nonNull(spaceAcceptance)){
            // 订单提交时间
            LocalDateTime orderTime = spaceAcceptance.getCreateTime();
            AtomicInteger serialNo = new AtomicInteger(1);
            WorkOrder workOrder = new WorkOrder();
            // 展会
            workOrder.setExhibitionManageId(spaceAcceptance.getExhibitionManageId());
            // 生成工单编号
            String workOrderNo = orderNumber +"-"+ serialNo;
            serialNo.getAndIncrement();
            workOrder.setWorkOrderNo(workOrderNo);
            workOrder.setOrderNumber(orderNumber);
            // 企业名称
            workOrder.setCustomerSubjectId(spaceAcceptance.getCompanyId());
            workOrder.setCustomerSubjectName(spaceAcceptance.getCompanyName());
            // 联系人
            workOrder.setContact(spaceAcceptance.getApplicationName());
            // 联系方式
            workOrder.setContactMobile(spaceAcceptance.getPhone());
            // 展厅号
            workOrder.setSpaceCode(spaceAcceptance.getSpaceCode());
            workOrder.setSpaceName(spaceAcceptance.getSpaceName());
            // 工单类型
            workOrder.setWorkOrderType(WorkOrderWorkOrderTypeEnum.CHECK);
            // 工单状态
            workOrder.setWorkOrderStatus(WorkOrderWorkOrderStatusEnum.ORDER_TO_BE_RECEIVED);
            // 工单接受方
            workOrder.setAcceptCompanyId(workOrderDTO.getAcceptCompanyId());
            workOrder.setAcceptCompanyName(workOrderDTO.getAcceptCompanyName());
            workOrder.setAcceptSubjectType(DataIsolationSystemSceneEnum.P_COMPOSITE_VENUE.getCode());
            BigDecimal workOrderAmount = BigDecimal.ZERO;
            // 生成操作记录
            WorkOrderOperationRecord workOrderOperationRecord = new WorkOrderOperationRecord();
            BeanUtil.copyProperties(workOrderDTO.getWorkOrderOperationRecordDTO(),workOrderOperationRecord);
            workOrderOperationRecord.setWorkOrderNo(workOrderNo);
            workOrderOperationRecord.setOperationType(CREATE);
            workOrderOperationRecord.setOperationRecordType(WorkOrderOperationRecordOperationRecordTypeEnum.CREATE);
            workOrderOperationRecord.setLastLinkFinishTime(orderTime);
            workOrderOperationRecordService.save(workOrderOperationRecord);
            workOrder.setWorkOrderAmount(workOrderAmount);
            // 处理操作环节
            dealWorkOrderLink(workOrderDTO.getWorkOrderOperationRecordDTO(),WorkOrderLinkOperationTypeEnum.CREATE,workOrderNo);
            // 推部门负责人短信
            sendMsgToLeader(workOrder);
            save(workOrder);
        }
        // 更新加班记录的派工状态
        SpaceAcceptance updateEntity2 = new SpaceAcceptance();
        updateEntity2.setId(spaceAcceptance.getId());
        updateEntity2.setFinishStatus(SpaceAcceptanceFinishStatusEnum.HAS_DISPATCH);
        spaceAcceptanceService.updateById(updateEntity2);
    }

    /**
     * 生成报修工单
     * @param workOrderDTO
     */
    private void generateRepairWorkOrder(WorkOrderDTO workOrderDTO) {
        String repairReportNumber = workOrderDTO.getRepairReportNumber();
        // 获取保修详情
        RepairReport repairReport = repairReportService.getByReportRepairNumber(repairReportNumber);
        if(Objects.nonNull(repairReport)){
            // 订单提交时间
            LocalDateTime orderTime = repairReport.getCreateTime();
            AtomicInteger serialNo = new AtomicInteger(1);
            WorkOrder workOrder = new WorkOrder();
            // 展会
            workOrder.setExhibitionManageId(repairReport.getExhibitionManageId());
            // 生成工单编号
            String workOrderNo = repairReportNumber +"-"+ serialNo;
            serialNo.getAndIncrement();
            workOrder.setWorkOrderNo(workOrderNo);
            workOrder.setOrderNumber(repairReportNumber);
            // 企业名称
            workOrder.setCustomerSubjectId(repairReport.getCompanyId());
            workOrder.setCustomerSubjectName(repairReport.getCompanyName());
            workOrder.setCustomerSubjectType(repairReport.getCompanyType());
            // 联系人
            workOrder.setContact(repairReport.getContact());
            // 联系方式
            workOrder.setContactMobile(repairReport.getPhone());
            // 展厅号
            workOrder.setSpaceCode(repairReport.getSpaceCode());
            workOrder.setSpaceName(repairReport.getSpaceName());
            // 展位号
            workOrder.setSiteName(repairReport.getSiteName());
            // 工单类型
            workOrder.setWorkOrderType(WorkOrderWorkOrderTypeEnum.REPAIR);
            // 工单状态
            workOrder.setWorkOrderStatus(WorkOrderWorkOrderStatusEnum.ORDER_TO_BE_RECEIVED);
            // 工单接受方
            workOrder.setAcceptCompanyId(workOrderDTO.getAcceptCompanyId());
            workOrder.setAcceptCompanyName(workOrderDTO.getAcceptCompanyName());
            workOrder.setAcceptSubjectType(DataIsolationSystemSceneEnum.P_COMPOSITE_VENUE.getCode());
            BigDecimal workOrderAmount = BigDecimal.ZERO;
            // 保修图纸
            dealDrawing(repairReportNumber, workOrder, workOrderNo);
            // 服务详情
            WorkOrderServiceItem workOrderServiceItem = new WorkOrderServiceItem();
            workOrderServiceItem.setWorkOrderNo(workOrderNo);
            // 查询报馆记录
            ServiceBooking serviceBooking = serviceBookingService.getById(repairReport.getServiceBookingId());
            if(Objects.nonNull(serviceBooking)){
                BeanUtil.copyProperties(serviceBooking,workOrderServiceItem, CommonConstants.COMMON_IGNORE_PROPERTIES);
                workOrderServiceItem.setWorkOrderNo(workOrderNo);
                workOrderServiceItem.setNum(BigDecimal.valueOf(serviceBooking.getBookingNum()));
                workOrderServiceItem.setSubtotalServicePrice(workOrderServiceItem.getUnitPrice().multiply(workOrderServiceItem.getNum()));
                workOrderAmount = workOrderAmount.add(workOrderServiceItem.getSubtotalServicePrice());
                workOrderServiceItemService.save(workOrderServiceItem);
            }
            
            // 生成操作记录
            WorkOrderOperationRecord workOrderOperationRecord = new WorkOrderOperationRecord();
            BeanUtil.copyProperties(workOrderDTO.getWorkOrderOperationRecordDTO(),workOrderOperationRecord);
            workOrderOperationRecord.setWorkOrderNo(workOrderNo);
            workOrderOperationRecord.setOperationType(CREATE);
            workOrderOperationRecord.setOperationRecordType(WorkOrderOperationRecordOperationRecordTypeEnum.CREATE);
            workOrderOperationRecord.setLastLinkFinishTime(orderTime);
            workOrderOperationRecordService.save(workOrderOperationRecord);
            workOrder.setWorkOrderAmount(workOrderAmount);
            // 处理操作环节
            dealWorkOrderLink(workOrderDTO.getWorkOrderOperationRecordDTO(),WorkOrderLinkOperationTypeEnum.CREATE,workOrderNo);
            // 推部门负责人短信
            sendMsgToLeader(workOrder);
            save(workOrder);
        }
        // 更新加班记录的派工状态
        repairReportService.updateHasDispatch(repairReport.getRepairReportNumber());
    }

    /**
     * 处理图纸
     * @param repairReportNumber
     * @param workOrder
     * @param workOrderNo
     */
    private void dealDrawing(String repairReportNumber, WorkOrder workOrder, String workOrderNo) {
        AttachmentFileDTO attachmentFileDTO = new AttachmentFileDTO();
        attachmentFileDTO.setBusinessId(Long.parseLong(repairReportNumber));
        attachmentFileDTO.setBusinessType("repair_report");
        R<List<AttachmentFileVO>> r = attachmentFileFeign.queryAttachmentFile(attachmentFileDTO);
        if(r.getIsSuccess()){
            for (AttachmentFileVO attachmentFileVO : r.getData()) {
                WorkOrderDrawing workOrderDrawing = new WorkOrderDrawing();
                workOrderDrawing.setPicUrl(attachmentFileVO.getAttachmentUrl());
                workOrderDrawing.setSpaceCode(workOrder.getSpaceCode());
                workOrderDrawing.setSpaceName(workOrder.getSpaceName());
                workOrderDrawing.setSiteCode(workOrder.getSiteCode());
                workOrderDrawing.setSiteName(workOrder.getSiteName());
                workOrderDrawing.setPicName(attachmentFileVO.getAttachmentName());
                workOrderDrawing.setPicSource("BOOKING");
                workOrderDrawing.setWorkOrderNo(workOrderNo);
                workOrderDrawingService.save(workOrderDrawing);
            }
        }
    }

    /**
     *
     * @param workOrderOperationRecordDTO
     * @param operationType
     * @param workOrderNo
     */
    private void dealWorkOrderLink(WorkOrderOperationRecordDTO workOrderOperationRecordDTO,WorkOrderLinkOperationTypeEnum operationType,String workOrderNo) {
        LocalDateTime now=LocalDateTime.now();
        if (operationType.eq(WorkOrderLinkOperationTypeEnum.ACCEPT)) {
            // 作废历史环节
            removeWorkOrderLink(workOrderNo,WorkOrderLinkOperationTypeEnum.ACCEPT);
            WorkOrderLink workOrderLink = new WorkOrderLink();
            BeanUtil.copyProperties(workOrderOperationRecordDTO, workOrderLink);
            workOrderLink.setWorkOrderNo(workOrderNo);
            workOrderLink.setOperationType(WorkOrderLinkOperationTypeEnum.ACCEPT);
            workOrderLink.setOperationTime(now);
            workOrderLinkService.save(workOrderLink);
            // 作废历史环节
            removeWorkOrderLink(workOrderNo,WorkOrderLinkOperationTypeEnum.DISPOSAL);
            WorkOrderLink workOrderLink2 = new WorkOrderLink();
            BeanUtil.copyProperties(workOrderOperationRecordDTO, workOrderLink2);
            workOrderLink2.setUserId(workOrderOperationRecordDTO.getReassignUserId());
            workOrderLink2.setUserName(workOrderOperationRecordDTO.getReassignUserName());
            workOrderLink2.setOrgId(workOrderOperationRecordDTO.getOrgId());
            workOrderLink2.setOrgName(workOrderOperationRecordDTO.getOrgName());
            workOrderLink2.setWorkOrderNo(workOrderNo);
            workOrderLink2.setOperationType(WorkOrderLinkOperationTypeEnum.DISPOSAL);
            workOrderLinkService.save(workOrderLink2);
        } else if(operationType.eq(WorkOrderLinkOperationTypeEnum.FINISH)){
            removeWorkOrderLink(workOrderNo,WorkOrderLinkOperationTypeEnum.FINISH);
            WorkOrderLink workOrderLink = new WorkOrderLink();
            BeanUtil.copyProperties(workOrderOperationRecordDTO, workOrderLink);
            workOrderLink.setWorkOrderNo(workOrderNo);
            workOrderLink.setOperationType(operationType);
            workOrderLink.setOperationTime(now);
            workOrderLinkService.save(workOrderLink);
            // 更新处理操作时间
            workOrderLinkService.update(new UpdateWrapper<WorkOrderLink>().lambda()
                    .eq(WorkOrderLink::getWorkOrderNo,workOrderNo)
                    .eq(WorkOrderLink::getOperationType,WorkOrderLinkOperationTypeEnum.DISPOSAL)
                    .set(WorkOrderLink::getIsDeleted,BusinessConstant.NO)
                    .set(WorkOrderLink::getOperationTime,now));
        } else if(operationType.eq(WorkOrderLinkOperationTypeEnum.REASSIGN)){
            removeWorkOrderLink(workOrderNo,WorkOrderLinkOperationTypeEnum.ACCEPT);
            removeWorkOrderLink(workOrderNo,WorkOrderLinkOperationTypeEnum.DISPOSAL);
            // 判断是派部门，还是派人员
            if (Objects.nonNull(workOrderOperationRecordDTO.getReassignUserId())) {
                WorkOrderLink workOrderLink = new WorkOrderLink();
                BeanUtil.copyProperties(workOrderOperationRecordDTO, workOrderLink);
                workOrderLink.setWorkOrderNo(workOrderNo);
                workOrderLink.setOperationType(WorkOrderLinkOperationTypeEnum.ACCEPT);
                workOrderLink.setOperationTime(now);
                workOrderLinkService.save(workOrderLink);
                WorkOrderLink workOrderLink2 = new WorkOrderLink();
                BeanUtil.copyProperties(workOrderOperationRecordDTO, workOrderLink2);
                workOrderLink2.setUserId(workOrderOperationRecordDTO.getReassignUserId());
                workOrderLink2.setUserName(workOrderOperationRecordDTO.getReassignUserName());
                workOrderLink2.setWorkOrderNo(workOrderNo);
                workOrderLink2.setOperationType(WorkOrderLinkOperationTypeEnum.DISPOSAL);
                workOrderLinkService.save(workOrderLink2);
            }
        }else {
            removeWorkOrderLink(workOrderNo,operationType);
            WorkOrderLink workOrderLink = new WorkOrderLink();
            BeanUtil.copyProperties(workOrderOperationRecordDTO, workOrderLink);
            workOrderLink.setWorkOrderNo(workOrderNo);
            workOrderLink.setOperationType(operationType);
            workOrderLink.setOperationTime(now);
            workOrderLinkService.save(workOrderLink);
        }
    }

    private void removeWorkOrderLink(String workOrderNo, WorkOrderLinkOperationTypeEnum operationType) {
        workOrderLinkService.update(new UpdateWrapper<WorkOrderLink>().lambda()
                .eq(WorkOrderLink::getWorkOrderNo,workOrderNo)
                .eq(WorkOrderLink::getOperationType,operationType)
                .set(WorkOrderLink::getIsDeleted,BusinessConstant.NO)
                .set(WorkOrderLink::getIsDeleted,BusinessConstant.YES));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer generateWorkOrderBatch(List<WorkOrderDTO> workOrderDTOS) {
        Integer resultNum = 0;
        for (WorkOrderDTO workOrderDTO : workOrderDTOS) {
            resultNum += generateWorkOrder(workOrderDTO);
        }
        return resultNum;
    }

    @Override
    public List<WorkOrderVO> queryFinishCompany(Long exhibitionManageId) {
        return baseMapper.queryFinishCompany(exhibitionManageId);
    }

    @Override
    public Page<WorkOrderVO> queryWorkOrder(PageParams<WorkOrderQuery> workOrderQuery) {
        workOrderQuery.setSort("createTime");
        workOrderQuery.setOrder("descending");
        WorkOrderQuery model = workOrderQuery.getModel();
        Page<WorkOrder> workOrderPage = workOrderQuery.buildPage();
        QueryWrapper<WorkOrder> queryWrapper = new QueryWrapper<>();
        List<Long> acceptCompanyIds = new ArrayList<>();
        if (Objects.nonNull(model.getAcceptCompanyId())) {
            acceptCompanyIds.add(model.getAcceptCompanyId());
            OrganizationDTO organizationDTO = new OrganizationDTO();
            organizationDTO.setOrgId(model.getAcceptCompanyId());
            R<List<Long>> listR = authServiceFeign.queryChildOrgIdOfOrgId(organizationDTO);
            if (listR.getIsSuccess() && CollectionUtils.isNotEmpty(listR.getData())) {
                acceptCompanyIds.addAll(listR.getData());
            }
        }
        queryWrapper.lambda().eq(WorkOrder::getIsDeleted,BusinessConstant.NO)
                // 展会ID
                .eq(Objects.nonNull(model.getExhibitionManageId()),WorkOrder::getExhibitionManageId,model.getExhibitionManageId())
                // 展厅号
                .eq(StringUtils.isNotBlank(model.getSpaceName()), WorkOrder::getSpaceName,model.getSpaceName())
                // 所属服务部门/商
                .in(Objects.nonNull(model.getAcceptCompanyId()), WorkOrder::getAcceptCompanyId,acceptCompanyIds)
                // 工单类型
                .eq(Objects.nonNull(model.getWorkOrderType()), WorkOrder::getWorkOrderType,model.getWorkOrderType())
                // 工单状态
                .eq(Objects.nonNull(model.getWorkOrderStatus()), WorkOrder::getWorkOrderStatus,model.getWorkOrderStatus())
                .ge(Objects.nonNull(model.getCreateTimeStart()), SuperEntity::getCreateTime, model.getCreateTimeStart())
                .le(Objects.nonNull(model.getCreateTimeEnd()), SuperEntity::getCreateTime, model.getCreateTimeEnd())
                // 关键词
                .and(StringUtils.isNotBlank(model.getKeywords()),
                        e->e.like(WorkOrder::getWorkOrderNo,model.getKeywords())
                                .or().like(WorkOrder::getCustomerSubjectName,model.getKeywords())
                                .or().like(WorkOrder::getContact,model.getKeywords())
                                .or().like(WorkOrder::getContactMobile,model.getKeywords())
                                .or().like(WorkOrder::getSpaceName,model.getKeywords())
                                .or().like(WorkOrder::getSiteName,model.getKeywords()));
        Page<WorkOrder> page = page(workOrderPage, queryWrapper);
        List<WorkOrder> records = page.getRecords();
        List<WorkOrderVO> workOrderVOS = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(records)){
            List<Long> exhibitionManageIds = records.stream().map(WorkOrder::getExhibitionManageId).collect(Collectors.toList());
            List<ExhibitionManage> exhibitionManages = exhibitionManageService.list(new QueryWrapper<ExhibitionManage>().lambda().in(SuperEntity::getId, exhibitionManageIds));
            Map<Long, ExhibitionManage> exhibitionManageMap = exhibitionManages.stream().collect(Collectors.toMap(SuperEntity::getId, Function.identity()));
            for (WorkOrder workOrder : records) {
                // A视角和C视角看工单的状态可能不太一样，B撤销C以后，C看工单状态是已撤销，但A还是待处理。A撤销以后，A\B\C看到的已撤销
                WorkOrderVO workOrderVO = BeanUtil.copyProperties(workOrder, WorkOrderVO.class);
                if(workOrderVO.getWorkOrderStatus().eq(WorkOrderWorkOrderStatusEnum.REVOKE)
                        && Objects.nonNull(workOrderVO.getAcceptCompanyId())
                        && model.getLoginUserId().equals(workOrder.getCreatedBy())){
                    // A视角和C视角看工单的状态可能不太一样，B撤销C以后，C看工单状态是已撤销，但A还是待处理。A撤销以后，A\B\C看到的已撤销
                    Long loginUserId = model.getLoginUserId();
                    dealUnAcceptOrDisposalStatus(workOrderVO, loginUserId);
                }
                ExhibitionManage exhibitionManage = exhibitionManageMap.get(workOrder.getExhibitionManageId());
                if(Objects.nonNull(exhibitionManage)){
                    workOrderVO.setExhibitionManageName(exhibitionManage.getExhibitionName());
                }
                // 处理方式
                if(Objects.nonNull(workOrder.getDisposalMode())){
                    workOrderVO.setDisposalModeName(workOrder.getDisposalMode().getDesc());
                }
                workOrderVOS.add(workOrderVO);
            }
        }
        Page<WorkOrderVO> workOrderVOPage = new Page<>();
        BeanUtil.copyProperties(page,workOrderVOPage);
        workOrderVOPage.setRecords(workOrderVOS);
        return workOrderVOPage;
    }


    private void dealUnAcceptOrDisposalStatus(WorkOrderVO workOrderVO, Long loginUserId) {
        // 处理工单环节
        setLink(workOrderVO);
        // 非接单人和处理人视角处理
        if (workOrderVO.getWorkOrderStatus().eq(WorkOrderWorkOrderStatusEnum.REVOKE)
                && Objects.nonNull(workOrderVO.getAcceptCompanyId())){
            WorkOrderLinkVO acceptLink = workOrderVO.getAcceptLink();
            WorkOrderLinkVO disposalLink = workOrderVO.getDisposalLink();
            if(Objects.nonNull(acceptLink) && Objects.nonNull(acceptLink.getUserId()) && !acceptLink.getUserId().equals(loginUserId)
                    && Objects.nonNull(disposalLink) && Objects.nonNull(disposalLink.getUserId()) && !disposalLink.getUserId().equals(loginUserId)){
                workOrderVO.setWorkOrderStatus(WorkOrderWorkOrderStatusEnum.ORDER_TO_BE_RECEIVED);
                workOrderVO.setDisposalLink(null);
            }
        }
    }

    @Override
    public WorkOrderVO queryWorkOrderDetail(WorkOrderQuery workOrderQuery) {
        // 查询工单
        WorkOrder workOrder = getOne(new QueryWrapper<WorkOrder>().lambda()
                .eq(WorkOrder::getIsDeleted, BusinessConstant.NO)
                .eq(WorkOrder::getWorkOrderNo, workOrderQuery.getWorkOrderNo()));
        WorkOrderVO workOrderVO = new WorkOrderVO();
        BeanUtil.copyProperties(workOrder, workOrderVO);
        // 查询工单服务
        List<WorkOrderServiceItem> workOrderServiceItems = workOrderServiceItemService.list(new QueryWrapper<WorkOrderServiceItem>().lambda()
                .eq(WorkOrderServiceItem::getIsDeleted, BusinessConstant.NO)
                .eq(WorkOrderServiceItem::getWorkOrderNo, workOrderQuery.getWorkOrderNo()));
        List<WorkOrderServiceItemVO> workOrderServiceItemVOS = ConvertUtil.convertList(workOrderServiceItems, WorkOrderServiceItemVO.class);
        // 查询工单操作记录
        List<WorkOrderOperationRecord> workOrderOperationRecords = workOrderOperationRecordService.list(new QueryWrapper<WorkOrderOperationRecord>().lambda()
                .eq(WorkOrderOperationRecord::getIsDeleted, BusinessConstant.NO)
                .eq(WorkOrderOperationRecord::getWorkOrderNo, workOrderQuery.getWorkOrderNo())
                .orderByDesc(WorkOrderOperationRecord::getCreateTime));
        List<WorkOrderOperationRecordVO> workOrderOperationRecordVOS = ConvertUtil.convertList(workOrderOperationRecords, WorkOrderOperationRecordVO.class);
        // 特殊格式处理
        Map<LocalDate, List<WorkOrderOperationRecord>> map = workOrderOperationRecords.stream().collect(Collectors.groupingBy(e -> e.getCreateTime().toLocalDate()));
        List<Map<String, Object>> list = new ArrayList<>(8);
        map.forEach((key, value) -> {
            Map<String, Object> stringObjectHashMap = new HashMap<>();
            stringObjectHashMap.put("time",key);
            stringObjectHashMap.put("children",value);
            list.add(stringObjectHashMap);
        });
        List<Map<String, Object>> reverseList = list.stream().sorted(Comparator.comparing(e->(LocalDate)e.get("time"))).collect(Collectors.toList());
        reverseList = Lists.<Map<String, Object>>reverse(reverseList);
        // 查询工单图纸
        List<WorkOrderDrawing> workOrderDrawingList = workOrderDrawingService.list(new QueryWrapper<WorkOrderDrawing>().lambda()
                .eq(WorkOrderDrawing::getIsDeleted, BusinessConstant.NO)
                .eq(WorkOrderDrawing::getWorkOrderNo, workOrderQuery.getWorkOrderNo()));
        List<WorkOrderDrawingVO> workOrderDrawingVOS = ConvertUtil.convertList(workOrderDrawingList, WorkOrderDrawingVO.class);
        // 查询工单加班明细
        List<WorkOrderWorkOvertime> workOrderWorkOvertimes = workOrderWorkOvertimeService.list(new QueryWrapper<WorkOrderWorkOvertime>().lambda()
                .eq(WorkOrderWorkOvertime::getIsDeleted, BusinessConstant.NO)
                .eq(WorkOrderWorkOvertime::getWorkOrderNo, workOrderQuery.getWorkOrderNo()));
        List<WorkOrderWorkOvertimeVO> workOrderWorkOvertimeVOS = ConvertUtil.convertList(workOrderWorkOvertimes, WorkOrderWorkOvertimeVO.class);
        workOrderVO.setWorkOrderServiceItemVOS(workOrderServiceItemVOS);
        workOrderVO.setWorkOrderOperationRecordVOS(workOrderOperationRecordVOS);
        workOrderVO.setWorkOrderOperationRecordMap(reverseList);
        workOrderVO.setWorkOrderDrawingVOS(workOrderDrawingVOS);
        workOrderVO.setWorkOrderWorkOvertimeVOS(workOrderWorkOvertimeVOS);
        // A视角和C视角看工单的状态可能不太一样，B撤销C以后，C看工单状态是已撤销，但A还是待处理。A撤销以后，A\B\C看到的已撤销
        Long loginUserId = workOrderQuery.getLoginUserId();
        // 处理工单环节
        dealUnAcceptOrDisposalStatus(workOrderVO, loginUserId);
        return workOrderVO;
    }

    @Override
    public List<WorkOrder> listByOrderNumber(String orderNumber) {
        QueryWrapper<WorkOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .lambda()
                .eq(WorkOrder::getIsDeleted, BusinessConstant.DELETE_NO)
                .eq(StrUtil.isNotBlank(orderNumber), WorkOrder::getOrderNumber, orderNumber)
        ;
        return list(queryWrapper);
    }

    private void setLink(WorkOrderVO workOrderVO) {
        List<WorkOrderLink> list = workOrderLinkService.list(new QueryWrapper<WorkOrderLink>().lambda()
                .eq(WorkOrderLink::getIsDeleted, BusinessConstant.NO)
                .eq(WorkOrderLink::getWorkOrderNo, workOrderVO.getWorkOrderNo()));
        for (WorkOrderLink workOrderLink : list) {
            WorkOrderLinkVO workOrderLinkVO = BeanUtil.copyProperties(workOrderLink, WorkOrderLinkVO.class);
            WorkOrderLinkOperationTypeEnum operationType = workOrderLink.getOperationType();
            if (Objects.nonNull(operationType)) {
                String code = operationType.getCode();
                switch (WorkOrderOperationRecordOperationTypeEnum.get(code)) {
                    case CREATE:
                        workOrderVO.setCreateLink(workOrderLinkVO);
                        break;
                    case ACCEPT:
                    case RETURN:
                        if(!workOrderVO.getWorkOrderStatus().eq(WorkOrderWorkOrderStatusEnum.ORDER_TO_BE_RECEIVED)){
                            workOrderVO.setAcceptLink(workOrderLinkVO);
                        }
                        break;
                    case DISPOSAL:
                        workOrderVO.setDisposalLink(workOrderLinkVO);
                        break;
                    case FINISH:
                        workOrderVO.setFinishLink(workOrderLinkVO);
                        break;
                    case REVOKE:
                        workOrderVO.setRevokeLink(workOrderLinkVO);
                        break;
                    case CANCEL:
                        workOrderVO.setCancelLink(workOrderLinkVO);
                    default:
                        break;
                }
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean receiveWorkOrder(WorkOrderOperationRecordDTO workOrderOperationRecordDTO) {
        String workOrderNo = workOrderOperationRecordDTO.getWorkOrderNo();
        // 查询工单详情
        WorkOrder workOrder =  getByWorkOrderNo(workOrderNo);
        // 修改工单状态
        updateWorkOrderStatus(workOrderNo,WorkOrderWorkOrderStatusEnum.PENDING,workOrderOperationRecordDTO.getWorkOrderDesc());
        WorkOrderOperationRecord workOrderOperationRecord = new WorkOrderOperationRecord();
        BeanUtil.copyProperties(workOrderOperationRecordDTO,workOrderOperationRecord);
        workOrderOperationRecord.setOperationType(WorkOrderOperationRecordOperationTypeEnum.ACCEPT);
        // 处理方式
        dealDisposalMode(workOrderOperationRecordDTO, workOrderNo);
        // 更新订单或加班明细派工状态
        updateWorkOrderStatus(workOrder, workOrder.getWorkOrderType(), workOrderNo, ServiceOrderWorkOrderStatusEnum.HAS_RECEIVE, workOrderOperationRecordDTO.getDisposalResult());
        // 处理操作环节
        dealWorkOrderLink(workOrderOperationRecordDTO,WorkOrderLinkOperationTypeEnum.ACCEPT,workOrderNo);
        // 推短信
        sendMsgForUser(getById(workOrder.getId()),workOrderOperationRecordDTO.getUserId());
        return insertOperationRecord(workOrderOperationRecord, workOrderOperationRecordDTO, workOrderNo);
    }

    /**
     * 处理方式
     * @param workOrderOperationRecordDTO
     * @param workOrderNo
     */
    private void dealDisposalMode(WorkOrderOperationRecordDTO workOrderOperationRecordDTO, String workOrderNo) {
        // 修改服务处理方式
        workOrderServiceItemService.update(new UpdateWrapper<WorkOrderServiceItem>().lambda().
                eq(WorkOrderServiceItem::getIsDeleted,BusinessConstant.NO).
                eq(WorkOrderServiceItem::getWorkOrderNo, workOrderNo).
                set(WorkOrderServiceItem::getDisposalMode, workOrderOperationRecordDTO.getDisposalMode()));
        // 修改加班处理方式
        workOrderWorkOvertimeService.update(new UpdateWrapper<WorkOrderWorkOvertime>().lambda().
                eq(WorkOrderWorkOvertime::getIsDeleted,BusinessConstant.NO).
                eq(WorkOrderWorkOvertime::getWorkOrderNo, workOrderNo).
                set(WorkOrderWorkOvertime::getDisposalMode, workOrderOperationRecordDTO.getDisposalMode()));
        // 更新工单处理方式
        update(new UpdateWrapper<WorkOrder>().lambda().
                eq(WorkOrder::getIsDeleted,BusinessConstant.NO).
                eq(WorkOrder::getWorkOrderNo, workOrderNo).
                set(WorkOrder::getDisposalMode, workOrderOperationRecordDTO.getDisposalMode()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean reassign(WorkOrderOperationRecordDTO workOrderOperationRecordDTO) {
        String workOrderNo = workOrderOperationRecordDTO.getWorkOrderNo();
        // 查询工单详情
        WorkOrder workOrder =  getByWorkOrderNo(workOrderNo);
        Long reassignUserId = workOrderOperationRecordDTO.getReassignUserId();
        if(Objects.nonNull(reassignUserId)){
            // 重新派工给人员
            // 更新工单
            WorkOrder updateEntity = new WorkOrder();
            updateEntity.setId(workOrder.getId());
            // 工单状态更新为待处理
            updateEntity.setWorkOrderStatus(WorkOrderWorkOrderStatusEnum.PENDING);
            updateById(updateEntity);
            //插入两条操作记录
            // 重新派单记录
            WorkOrderOperationRecord workOrderOperationRecord = new WorkOrderOperationRecord();
            BeanUtil.copyProperties(workOrderOperationRecordDTO,workOrderOperationRecord);
            workOrderOperationRecord.setOperationRecordType(WorkOrderOperationRecordOperationRecordTypeEnum.REASSIGN);
            insertOperationRecord(workOrderOperationRecord, workOrderOperationRecordDTO, workOrderNo);
            // 指派接单记录
            workOrderOperationRecordDTO.setLastLinkFinishTime(LocalDateTime.now());
            WorkOrderOperationRecord workOrderOperationRecord2 = new WorkOrderOperationRecord();
            BeanUtil.copyProperties(workOrderOperationRecordDTO,workOrderOperationRecord2);
            workOrderOperationRecord2.setOperationRecordType(WorkOrderOperationRecordOperationRecordTypeEnum.ACCEPT);
            insertOperationRecord(workOrderOperationRecord2, workOrderOperationRecordDTO, workOrderNo);
            // 处理方式
            dealDisposalMode(workOrderOperationRecordDTO,workOrderNo);
            // 更新订单或加班明细派工状态
            updateWorkOrderStatus(workOrder, workOrder.getWorkOrderType(), workOrderNo, ServiceOrderWorkOrderStatusEnum.HAS_RECEIVE, workOrderOperationRecordDTO.getDisposalResult());
            // 推站内信
            sendMsgForUser(getById(workOrder.getId()),reassignUserId);
        }else{
            // 重新派工给部门
            WorkOrder updateEntity = new WorkOrder();
            updateEntity.setId(workOrder.getId());
            // 重新派工给部门
            updateEntity.setAcceptCompanyId(workOrderOperationRecordDTO.getReassignOrgId());
            updateEntity.setAcceptCompanyName(workOrderOperationRecordDTO.getReassignOrgName());
            // 工单状态更新为待接单
            updateEntity.setWorkOrderStatus(WorkOrderWorkOrderStatusEnum.ORDER_TO_BE_RECEIVED);
            updateById(updateEntity);
            // 插入特定的操作记录
            WorkOrderOperationRecord workOrderOperationRecord = new WorkOrderOperationRecord();
            BeanUtil.copyProperties(workOrderOperationRecordDTO,workOrderOperationRecord);
            workOrderOperationRecord.setOperationRecordType(WorkOrderOperationRecordOperationRecordTypeEnum.REASSIGN);
            insertOperationRecord(workOrderOperationRecord, workOrderOperationRecordDTO, workOrderNo);
            // 更新订单或加班明细派工状态
            updateWorkOrderStatus(workOrder, workOrder.getWorkOrderType(), workOrderNo, ServiceOrderWorkOrderStatusEnum.HAS_DISPATCH, workOrderOperationRecordDTO.getDisposalResult());
            // 推站内信
            sendInnerMsgForOrg(getById(workOrder.getId()));
        }
        // 处理操作环节
        dealWorkOrderLink(workOrderOperationRecordDTO,WorkOrderLinkOperationTypeEnum.REASSIGN,workOrderNo);
        return true;
    }

    private WorkOrder getByWorkOrderNo(String workOrderNo) {
        WorkOrder workOrder = getOne(new QueryWrapper<WorkOrder>().lambda()
                .eq(WorkOrder::getIsDeleted, BusinessConstant.NO)
                .eq(WorkOrder::getWorkOrderNo, workOrderNo));
        return workOrder;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean revokeWorkOrder(WorkOrderOperationRecordDTO workOrderOperationRecordDTO) {
        String workOrderNo = workOrderOperationRecordDTO.getWorkOrderNo();
        // 查询工单详情
        WorkOrder workOrder =  getByWorkOrderNo(workOrderNo);
        // 修改工单状态
        updateWorkOrderStatus(workOrderNo,WorkOrderWorkOrderStatusEnum.REVOKE,null);
        WorkOrderOperationRecord workOrderOperationRecord = new WorkOrderOperationRecord();
        BeanUtil.copyProperties(workOrderOperationRecordDTO,workOrderOperationRecord);
        workOrderOperationRecord.setOperationType(WorkOrderOperationRecordOperationTypeEnum.REVOKE);
        WorkOrderWorkOrderTypeEnum workOrderType = workOrder.getWorkOrderType();
        // 更新订单或加班明细派工状态
        updateWorkOrderStatus(workOrder, workOrderType, workOrderNo, ServiceOrderWorkOrderStatusEnum.HAS_DISPATCH, workOrderOperationRecordDTO.getDisposalResult());
        // 处理方式
        dealDisposalMode(workOrderOperationRecordDTO,workOrderNo);
        // 处理操作环节
        dealWorkOrderLink(workOrderOperationRecordDTO,WorkOrderLinkOperationTypeEnum.REVOKE,workOrderNo);
        return insertOperationRecord(workOrderOperationRecord, workOrderOperationRecordDTO, workOrderNo);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean returnWorkOrder(WorkOrderOperationRecordDTO workOrderOperationRecordDTO) {
        String workOrderNo = workOrderOperationRecordDTO.getWorkOrderNo();
        // 查询工单详情
        WorkOrder workOrder =  getByWorkOrderNo(workOrderNo);
        // 修改工单状态
        updateWorkOrderStatus(workOrderNo,WorkOrderWorkOrderStatusEnum.RETURN,null);
        WorkOrderOperationRecord workOrderOperationRecord = new WorkOrderOperationRecord();
        BeanUtil.copyProperties(workOrderOperationRecordDTO,workOrderOperationRecord);
        workOrderOperationRecord.setOperationType(WorkOrderOperationRecordOperationTypeEnum.RETURN);
        WorkOrderWorkOrderTypeEnum workOrderType = workOrder.getWorkOrderType();
        // 更新订单或加班明细派工状态
        updateWorkOrderStatus(workOrder, workOrderType, workOrderNo, ServiceOrderWorkOrderStatusEnum.HAS_DISPATCH, workOrderOperationRecordDTO.getDisposalResult());
        // 处理方式
        dealDisposalMode(workOrderOperationRecordDTO,workOrderNo);
        // 处理操作环节
        dealWorkOrderLink(workOrderOperationRecordDTO,WorkOrderLinkOperationTypeEnum.RETURN,workOrderNo);
        return insertOperationRecord(workOrderOperationRecord, workOrderOperationRecordDTO, workOrderNo);
    }

    @Override
    public Boolean smsReminder(WorkOrderDTO workOrderDTO) {
        try{
            WorkOrder workOrder = getById(workOrderDTO.getId());
            sendMsgToLeader(workOrder);
        }catch (Exception e){
            log.error("发送短信失败",e);
            return false;
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean revokeWorkOrderByPromoter(WorkOrderOperationRecordDTO workOrderOperationRecordDTO) {
        String workOrderNo = workOrderOperationRecordDTO.getWorkOrderNo();
        // 查询工单详情
        WorkOrder workOrder =  getByWorkOrderNo(workOrderNo);
        // 清除工单绑定的部门服务商
        update(new UpdateWrapper<WorkOrder>().lambda()
                .eq(SuperEntity::getId,workOrder.getId())
                .set(WorkOrder::getAcceptCompanyId,null)
                .set(WorkOrder::getWorkOrderStatus,WorkOrderWorkOrderStatusEnum.REVOKE)
                .set(WorkOrder::getAcceptCompanyName,null));
        WorkOrderOperationRecord workOrderOperationRecord = new WorkOrderOperationRecord();
        BeanUtil.copyProperties(workOrderOperationRecordDTO,workOrderOperationRecord);
        workOrderOperationRecord.setOperationType(WorkOrderOperationRecordOperationTypeEnum.REVOKE);
        WorkOrderWorkOrderTypeEnum workOrderType = workOrder.getWorkOrderType();
        // 更新订单或加班明细派工状态
        updateWorkOrderStatus(workOrder, workOrderType, workOrderNo, ServiceOrderWorkOrderStatusEnum.REVOKE, workOrderOperationRecordDTO.getDisposalResult());
        // 处理操作环节
        dealWorkOrderLink(workOrderOperationRecordDTO,WorkOrderLinkOperationTypeEnum.REVOKE,workOrderNo);
        return insertOperationRecord(workOrderOperationRecord, workOrderOperationRecordDTO, workOrderNo);
    }

    /**
     * 更新订单或加班明细派工状态
     * @param workOrder
     * @param workOrderType
     * @param workOrderNo
     * @param disposalResult
     * @return
     */
    private ServiceOrderWorkOrderStatusEnum updateWorkOrderStatus(WorkOrder workOrder, WorkOrderWorkOrderTypeEnum workOrderType, String workOrderNo, ServiceOrderWorkOrderStatusEnum toUpdateStatus, WorkOrderOperationRecordDisposalResultEnum disposalResult) {
        workOrder = getById(workOrder.getId());
        String orderNumber = workOrder.getOrderNumber();
        // 判断工单是否没了部门，如果是，订单为已撤销
        if (Objects.isNull(workOrder.getAcceptCompanyId()) && !toUpdateStatus.eq(ServiceOrderWorkOrderStatusEnum.CANCEL)) {
            toUpdateStatus = ServiceOrderWorkOrderStatusEnum.REVOKE;
        }
        // 更新订单
        if (workOrderType.eq(WorkOrderWorkOrderTypeEnum.SERVICE)) {
            if (StringUtils.isNotBlank(orderNumber)) {
                // 订单
                ServiceOrder serviceOrder = serviceOrderService.getByOrderNumber(orderNumber);
                List<String> distinctStatus  =baseMapper.getDistinctStatus(new QueryWrapper<WorkOrder>()
                        .eq("is_deleted", BusinessConstant.NO)
                        .eq("order_number", orderNumber));
                if (CollectionUtils.isNotEmpty(distinctStatus)) {
                    if (distinctStatus.size()==1 && distinctStatus.contains(WorkOrderWorkOrderStatusEnum.FINISH.getCode())) {
                        // 如果只存在已完成，则订单状态为已完成
                        toUpdateStatus = ServiceOrderWorkOrderStatusEnum.COMPLETE;
                    } else if (distinctStatus.contains(WorkOrderWorkOrderStatusEnum.FINISH.getCode())) {
                        // 如果存在已完成，则订单状态为部分完成
                        toUpdateStatus = ServiceOrderWorkOrderStatusEnum.PARTIAL_COMPLETE;
                    } else if (distinctStatus.contains(WorkOrderWorkOrderStatusEnum.PENDING.getCode())) {
                        // 如果不存在已完成，且存在待处理，则订单状态为已接单
                        toUpdateStatus = ServiceOrderWorkOrderStatusEnum.HAS_RECEIVE;
                    } else if (distinctStatus.contains(WorkOrderWorkOrderStatusEnum.ORDER_TO_BE_RECEIVED.getCode())) {
                        // 如果不存在已完成、待处理，存在待接单，则订单状态为已派单
                        toUpdateStatus = ServiceOrderWorkOrderStatusEnum.HAS_DISPATCH;
                    } else if (distinctStatus.size()==1 && distinctStatus.contains(WorkOrderWorkOrderStatusEnum.REVOKE.getCode())) {
                        // 判断工单是否没了部门，如果是，订单为已撤销
                        if (Objects.isNull(workOrder.getAcceptCompanyId())) {
                            toUpdateStatus = ServiceOrderWorkOrderStatusEnum.REVOKE;
                        }else {
                            toUpdateStatus = ServiceOrderWorkOrderStatusEnum.HAS_RECEIVE;
                        }
                    }else if (distinctStatus.size()==1 && distinctStatus.contains(WorkOrderWorkOrderStatusEnum.CANCEL.getCode())) {
                        // 如果不存在已完成、待处理、待接单，只存在已作废，则订单状态为已作废
                        toUpdateStatus = ServiceOrderWorkOrderStatusEnum.CANCEL;
                    }else{
                        //其他情况为已派单
                        toUpdateStatus = ServiceOrderWorkOrderStatusEnum.HAS_DISPATCH;
                    }
                }
                if (Objects.nonNull(serviceOrder)) {
                    // 更新订单的派工状态
                    venueManageServiceOrderService.updateWorkOrderStatus(serviceOrder.getOrderNumber(), toUpdateStatus);
                }
            }else {
                // 报馆记录
                serviceBookingService.updateWorkOrderStatus(workOrderNo,ServiceBookingWorkOrderStatusEnum.get(toUpdateStatus.getCode()));
            }
        }else if (workOrderType.eq(WorkOrderWorkOrderTypeEnum.WORK_OVERTIME)) {
            // 更新加班记录的派工状态
            WorkOvertime workOvertime = workOvertimeService.getByWorkOvertimeNumber(orderNumber);
            if(Objects.nonNull(workOvertime)){
                WorkOvertime updateEntity2 = new WorkOvertime();
                updateEntity2.setId(workOvertime.getId());
                updateEntity2.setWorkOrderStatus(toUpdateStatus.getCode());
                workOvertimeService.updateById(updateEntity2);
            }
        }else if(workOrderType.eq(WorkOrderWorkOrderTypeEnum.REPAIR)){
            // 更新报修记录的派工状态
            repairReportService.updateWorkOrderStatus(orderNumber, toUpdateStatus);
        }else if(workOrderType.eq(WorkOrderWorkOrderTypeEnum.REPAIR)){
            // 更新验收记录的派工状态
            spaceAcceptanceService.updateFinishStatus(orderNumber, SpaceAcceptanceFinishStatusEnum.FINISHED, Objects.nonNull(disposalResult) ? SpaceAcceptanceDealResultEnum.get(disposalResult.getCode()) : null);
        }
        return toUpdateStatus;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean cancelWorkOrder(WorkOrderOperationRecordDTO workOrderOperationRecordDTO) {
        String workOrderNo = workOrderOperationRecordDTO.getWorkOrderNo();
        // 查询工单详情
        WorkOrder workOrder =  getByWorkOrderNo(workOrderNo);
        // 修改工单状态
        updateWorkOrderStatus(workOrderNo,WorkOrderWorkOrderStatusEnum.CANCEL,null);
        WorkOrderOperationRecord workOrderOperationRecord = new WorkOrderOperationRecord();
        BeanUtil.copyProperties(workOrderOperationRecordDTO,workOrderOperationRecord);
        workOrderOperationRecord.setOperationType(WorkOrderOperationRecordOperationTypeEnum.CANCEL);
        WorkOrderWorkOrderTypeEnum workOrderType = workOrder.getWorkOrderType();
        // 更新订单或加班明细派工状态
        updateWorkOrderStatus(workOrder, workOrderType, workOrderNo, ServiceOrderWorkOrderStatusEnum.CANCEL, workOrderOperationRecordDTO.getDisposalResult());
        // 处理操作环节
        dealWorkOrderLink(workOrderOperationRecordDTO,WorkOrderLinkOperationTypeEnum.CANCEL,workOrderNo);
        return insertOperationRecord(workOrderOperationRecord, workOrderOperationRecordDTO, workOrderNo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean closeWorkOrder(WorkOrderOperationRecordDTO workOrderOperationRecordDTO) {
        String workOrderNo = workOrderOperationRecordDTO.getWorkOrderNo();
        // 查询工单详情
        WorkOrder workOrder =  getByWorkOrderNo(workOrderNo);
        // 修改工单状态
        updateWorkOrderStatus(workOrderNo,WorkOrderWorkOrderStatusEnum.FINISH,null);
        WorkOrderOperationRecord workOrderOperationRecord = new WorkOrderOperationRecord();
        BeanUtil.copyProperties(workOrderOperationRecordDTO,workOrderOperationRecord);
        workOrderOperationRecord.setOperationType(WorkOrderOperationRecordOperationTypeEnum.FINISH);
        WorkOrderWorkOrderTypeEnum workOrderType = workOrder.getWorkOrderType();
        // 更新订单或加班明细派工状态
        updateWorkOrderStatus(workOrder, workOrderType, workOrderNo, ServiceOrderWorkOrderStatusEnum.COMPLETE,workOrderOperationRecordDTO.getDisposalResult());
        // 处理操作环节
        dealWorkOrderLink(workOrderOperationRecordDTO,WorkOrderLinkOperationTypeEnum.FINISH,workOrderNo);
        // 如果是验收工单，更新验收记录
        if(workOrder.getWorkOrderType().eq(WorkOrderWorkOrderTypeEnum.CHECK)){
            SpaceAcceptance spaceAcceptance = spaceAcceptanceService.getByAcceptNo(workOrder.getOrderNumber());
            if(Objects.nonNull(spaceAcceptance)){
                SpaceAcceptance updateEntity = new SpaceAcceptance();
                updateEntity.setId(spaceAcceptance.getId());
                updateEntity.setDealResult(SpaceAcceptanceDealResultEnum.get(workOrderOperationRecordDTO.getDisposalResult().getCode()));
                updateEntity.setFinishStatus(SpaceAcceptanceFinishStatusEnum.FINISHED);
                spaceAcceptanceService.updateById(updateEntity);
            }
        }
        return insertOperationRecord(workOrderOperationRecord, workOrderOperationRecordDTO, workOrderNo);
    }

    private boolean insertOperationRecord(WorkOrderOperationRecord workOrderOperationRecord, WorkOrderOperationRecordDTO workOrderOperationRecordDTO, String workOrderNo) {
        // 如果操作记录类型为空，则赋值工单环节类型
        if(Objects.isNull(workOrderOperationRecord.getOperationRecordType())){
            workOrderOperationRecord.setOperationRecordType(WorkOrderOperationRecordOperationRecordTypeEnum.get(workOrderOperationRecord.getOperationType().getCode()));
        }
        // 查询最后一条操作记录的时间
        WorkOrderOperationRecord record = workOrderOperationRecordService.getOne(new QueryWrapper<WorkOrderOperationRecord>().lambda()
                .eq(WorkOrderOperationRecord::getWorkOrderNo, workOrderNo)
                .eq(WorkOrderOperationRecord::getIsDeleted, BusinessConstant.NO)
                .orderByDesc(SuperEntity::getCreateTime).last("limit 1"));
        if(Objects.nonNull(record)){
            workOrderOperationRecord.setLastLinkFinishTime(record.getCreateTime());
        }
        boolean flag = workOrderOperationRecordService.save(workOrderOperationRecord);
        // 操作环节类型
        WorkOrderOperationRecordOperationTypeEnum operationType = workOrderOperationRecordDTO.getOperationType();
        if(Objects.nonNull(operationType)){
            workOrderServiceItemService.update(new UpdateWrapper<WorkOrderServiceItem>().lambda()
                    .eq(WorkOrderServiceItem::getIsDeleted, BusinessConstant.NO)
                    .eq(WorkOrderServiceItem::getWorkOrderNo, workOrderNo)
                    .set(WorkOrderServiceItem::getDisposalMode,operationType));
        }
        return flag;
    }

    @Override
    public Boolean updateWorkOrder(WorkOrderDTO workOrderDTO) {
        if(Objects.nonNull(workOrderDTO.getId())){
            WorkOrder workOrder = new WorkOrder();
            BeanUtil.copyProperties(workOrderDTO,workOrder);
            if(StringUtils.isBlank(workOrder.getRemark())){
                workOrder.setRemark(Strings.EMPTY);
            }
           return updateById(workOrder);
        }
        return false;
    }

    /**
     * 修改工单状态
     * @param workOrderNo
     * @param workOrderStatus
     */
    private void updateWorkOrderStatus(String workOrderNo, WorkOrderWorkOrderStatusEnum workOrderStatus,String workOrderDesc) {
        update(new UpdateWrapper<WorkOrder>().lambda().eq(WorkOrder::getWorkOrderNo,workOrderNo)
                .eq(WorkOrder::getIsDeleted,BusinessConstant.NO)
                .set(WorkOrder::getWorkOrderStatus,workOrderStatus.getCode())
                .set(StringUtils.isNotBlank(workOrderDesc),WorkOrder::getWorkOrderDesc,workOrderDesc));
    }

    /**
     * 处理工单
     * @param workOrderOperationRecordDTO workOrderOperationRecordDTO
     * @param orderNumber orderNumber
     * @param workOrderDrawings workOrderDrawings
     * @param serviceOrder serviceOrder
     * @param serviceBookingVOS serviceBookingVOS
     * @param serviceBookingMap serviceBookingMap
     * @param serviceProviderMap serviceProviderMap
     * @param orgMap orgMap
     * @param serialNo serialNo
     */
    private Integer dealWorkOrder(WorkOrderOperationRecordDTO workOrderOperationRecordDTO, String orderNumber, List<WorkOrderDrawingDTO> workOrderDrawings, ServiceOrder serviceOrder, List<ServiceBookingVO> serviceBookingVOS, Map<Long, List<ServiceBookingVO>> serviceBookingMap, Map<Long, ServiceProviderVO> serviceProviderMap, Map<Long, OrganizationVo> orgMap, AtomicInteger serialNo) {
        AtomicReference<Integer> resultNum = new AtomicReference<>(0);
        // 订单提交时间
        LocalDateTime orderTime = serviceOrder.getOrderTime();
        serviceBookingMap.forEach((k, v) ->{
            WorkOrder workOrder = new WorkOrder();
            // 展会
            workOrder.setExhibitionManageId(serviceOrder.getExhibitionManageId());
            // 生成工单编号
            String workOrderNo = orderNumber +"-"+ serialNo;
            serialNo.getAndIncrement();
            workOrder.setWorkOrderNo(workOrderNo);
            workOrder.setOrderNumber(orderNumber);
            // 企业名称
            workOrder.setCustomerSubjectId(serviceOrder.getCompanyId());
            workOrder.setCustomerSubjectName(serviceOrder.getCompanyName());
            workOrder.setCustomerSubjectType(serviceOrder.getCompanyType());
            // 联系人
            workOrder.setContact(serviceOrder.getContact());
            // 联系方式
            workOrder.setContactMobile(serviceOrder.getPhone());
            // 展厅号
            workOrder.setSpaceCode(serviceOrder.getSpaceCode());
            workOrder.setSpaceName(serviceOrder.getSpaceName());
            // 展位号
            workOrder.setSiteName(serviceOrder.getSiteName());
            // 工单类型
            workOrder.setWorkOrderType(WorkOrderWorkOrderTypeEnum.SERVICE);
            // 工单状态
            workOrder.setWorkOrderStatus(WorkOrderWorkOrderStatusEnum.ORDER_TO_BE_RECEIVED);
            // 工单接受方
            workOrder.setAcceptCompanyId(k);
            ServiceProviderVO serviceProviderVO = serviceProviderMap.get(k);
            OrganizationVo organizationVo = orgMap.get(k);
            if(Objects.nonNull(serviceProviderVO)){
                workOrder.setAcceptCompanyName(serviceProviderVO.getCompanyName());
                workOrder.setAcceptSubjectType(DataIsolationSystemSceneEnum.P_COMPOSITE_MATING.getCode());
            }
            if(Objects.nonNull(organizationVo)){
                workOrder.setAcceptCompanyName(organizationVo.getName());
                workOrder.setAcceptSubjectType(DataIsolationSystemSceneEnum.P_COMPOSITE_VENUE.getCode());
            }
            BigDecimal workOrderAmount = BigDecimal.ZERO;
            // 服务项
            for (ServiceBookingVO serviceBookingVO : serviceBookingVOS) {
                if(serviceBookingVO.getServiceProviderId().equals(workOrder.getAcceptCompanyId())){
                    WorkOrderServiceItem workOrderServiceItem = new WorkOrderServiceItem();
                    BeanUtil.copyProperties(serviceBookingVO,workOrderServiceItem, CommonConstants.COMMON_IGNORE_PROPERTIES);
                    workOrderServiceItem.setWorkOrderNo(workOrderNo);
                    workOrderServiceItem.setNum(BigDecimal.valueOf(serviceBookingVO.getBookingNum()));
                    workOrderServiceItem.setSubtotalServicePrice(workOrderServiceItem.getUnitPrice().multiply(workOrderServiceItem.getNum()));
                    workOrderAmount = workOrderAmount.add(workOrderServiceItem.getSubtotalServicePrice());
                    workOrderServiceItemService.save(workOrderServiceItem);
                }
            }
            // 图纸
            if(CollectionUtils.isNotEmpty(workOrderDrawings)){
                workOrderDrawings.forEach(value ->{
                    WorkOrderDrawing workOrderDrawing = new WorkOrderDrawing();
                    BeanUtil.copyProperties(value,workOrderDrawing);
                    workOrderDrawing.setWorkOrderNo(workOrderNo);
                    workOrderDrawingService.save(workOrderDrawing);
                });
            }
            // 生成操作记录
            WorkOrderOperationRecord workOrderOperationRecord = new WorkOrderOperationRecord();
            BeanUtil.copyProperties(workOrderOperationRecordDTO,workOrderOperationRecord);
            workOrderOperationRecord.setWorkOrderNo(workOrderNo);
            workOrderOperationRecord.setOperationType(CREATE);
            workOrderOperationRecord.setOperationRecordType(WorkOrderOperationRecordOperationRecordTypeEnum.CREATE);
            workOrderOperationRecord.setLastLinkFinishTime(orderTime);
            workOrderOperationRecordService.save(workOrderOperationRecord);
            workOrder.setWorkOrderAmount(workOrderAmount);
            // 处理工单环节
            dealWorkOrderLink(workOrderOperationRecordDTO,WorkOrderLinkOperationTypeEnum.CREATE,workOrderNo);
            // 推部门负责人短信
            sendMsgToLeader(workOrder);
            save(workOrder);
            resultNum.updateAndGet(v1 -> v1 + 1);
        });
        return resultNum.get();
    }


    /**
     * do转vo
     * @param model model
     * @return modelVo
     */
    @Override
    public WorkOrderVO doToVo(WorkOrder model) {
        WorkOrderVO modelVo = new WorkOrderVO();
        BeanUtil.copyProperties(model, modelVo);
        modelVo.setId(model.getId());
        return modelVo;
    }
    /**
     * do转vo
     * @param modelList modelList
     * @return list
     */
     @Override
     public List<WorkOrderVO> doToVos(List<WorkOrder> modelList) {
        if (modelList == null || modelList.isEmpty()) {
        return null;
        }
        List<WorkOrderVO> result = new ArrayList<>();
        for (WorkOrder model : modelList) {
           result.add(doToVo(model));
        }
        return result;
    }
}
